package com.kjj.car.service.impl;

import com.kjj.basic.service.IBaiduAiService;
import com.kjj.basic.util.AjaxResult;
import com.kjj.basic.util.VelocityUtils;
import com.kjj.car.domain.*;
import com.kjj.car.dto.CarOnsaleOrOffsaleDto;
import com.kjj.car.es.doc.CarDoc;
import com.kjj.car.es.repository.CarRepository;
import com.kjj.car.mapper.CarDetailMapper;
import com.kjj.car.mapper.CarMapper;
import com.kjj.car.mapper.CarOnlineAuditLogMapper;
import com.kjj.car.mapper.CarTypeMapper;
import com.kjj.car.service.ICarService;
import com.kjj.basic.service.impl.BaseServiceImpl;
import com.kjj.org.domain.Shop;
import com.kjj.org.mapper.ShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kan
 * @since 2022-09-08
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car> implements ICarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private CarDetailMapper carDetailMapper;

    @Autowired
    private IBaiduAiService baiduAiService;

    @Autowired
    private CarOnlineAuditLogMapper logMapper;

    @Autowired
    private CarRepository carRepository;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private CarTypeMapper carTypeMapper;

    @Override
    public CarResources getResources(Long id) {
        return carMapper.loadResource(id);
    }

    @Override
    public void onsale(CarOnsaleOrOffsaleDto carDto) {
        //参数判断
        List<Long> ids = carDto.getIds();
        if (ids == null || ids.size()<1) {
            throw new RuntimeException("系统异常，参数不对");
        }
        //es中添加数据 @TODO
        List<CarDoc> carDocs = buildCarDocs(ids);
        carRepository.saveAll(carDocs);
        //修改数据库上架时间
        carMapper.onsale(ids);
        //添加日志
        addLogs(carDto,2);
        //页面静态化
        staticPages(carDto.getIds());
    }
    private void staticPages(List<Long> carIds) {
        //每个车要有一个静态化页面
        carIds.forEach(carId->{

            //模型 car
            Car car = carMapper.loadById(carId);

            //模板
            String tmplatePath = this.getClass().getClassLoader().getResource("").getPath()
                    +"/templates/carDetails.vm";
            System.out.println(tmplatePath);

            //静态化页面生成的路径
            String protalWebsitePath = "D:\\workspace_idea\\kjj-car-portal\\kjj-car-portal\\details\\";
            String htmlFilePath =protalWebsitePath + carId+ ".html";
            VelocityUtils.staticByTemplate(car,tmplatePath,htmlFilePath);
        });
    }

    @Override
    public void offsale(CarOnsaleOrOffsaleDto carDto) {
        //参数判断
        List<Long> ids = carDto.getIds();
        if (ids == null || ids.size()<1) {
            throw new RuntimeException("系统异常，参数不对");
        }
        //es中添加数据 @TODO
        List<CarDoc> carDocs = new ArrayList<>();
        ids.forEach(id->{
            CarDoc carDoc = new CarDoc();
            carDoc.setId(id);
        });
        carRepository.deleteAll(carDocs);
        //修改数据库上架时间
        carMapper.offsale(ids);
        //添加日志
        addLogs(carDto,3);
    }

    @Override
    public void delByCarId(Long id) {
        carMapper.removeByCarId(id);
    }

    private List<CarDoc> buildCarDocs(List<Long> ids) {
        List<CarDoc> result = new ArrayList<>();
        ids.forEach(carId->{
            result.add(buildCarDoc(carId));
        });
        return result;
    }
    private CarDoc buildCarDoc(Long carId) {
        Car car = carMapper.loadById(carId);//数据库
        CarDoc carDoc = new CarDoc();//es
        carDoc.setId(carId);
        carDoc.setTitle(car.getTitle());
        carDoc.setCover(car.getCover());
        carDoc.setSaleprice(car.getSaleprice());
        carDoc.setCostprice(car.getCostprice());
        carDoc.setIsnew(car.getIsnew());
        carDoc.setReigstertime(car.getReigstertime());
        carDoc.setMileage(car.getMileage());
        Shop shop = shopMapper.loadById(car.getShopId());
        carDoc.setShopId(shop.getId());
        carDoc.setShopName(shop.getName());
        carDoc.setShopAdress(shop.getAddress());
        carDoc.setOnsaletime(car.getOnsaletime());
        carDoc.setCosteffective(car.getCosteffective());
        carDoc.setRushsale(car.getRushsale());
        carDoc.setQuasinewcar(car.getQuasinewcar());
        carDoc.setTransitivecountry(car.getTransitivecountry());
        CarType carType = carTypeMapper.loadById(car.getTypeId());
        carDoc.setTypeId(carType.getId());
        carDoc.setTypeName(carType.getName());
        CarDetail detail = carDetailMapper.loadByCarId(carId);
        if (detail!=null)
            carDoc.setCarInfo(detail.getInfo());
        return carDoc;
    }

    private void addLogs(CarOnsaleOrOffsaleDto carOprDto,  int state) {
        List<CarOnlineAuditLog> logs = new ArrayList<>();
        carOprDto.getIds().forEach(id -> {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setState(state);//上架
            log.setAuditId(carOprDto.getOperatorId());
            log.setAuditTime(new Date());
            if (state==2)
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "进行了上架！");
            else if (state==3)
                log.setNote(carOprDto.getOperatorName() + "对id为" + id + "进行了下架！");
            logs.add(log);
        });

        logMapper.bulkSave(logs);
    }
    @Override
    @Transactional
    public void add(Car car) {
        CarDetail carDetail = car.getCarDetail();
        //审核
        String text = car.getTitle() +" "+ carDetail.getInfo();
        AjaxResult ajaxResult = baiduAiService.audit(text, car.getCover(), null);
        CarOnlineAuditLog log = new CarOnlineAuditLog();  //审核日志() 上下线日志
        log.setAuditTime(new Date());
        if (ajaxResult.isSuccess()){
            log.setState(1);
            log.setNote("系统审核通过！");
        }else
        {
            log.setState(-1); //
            log.setNote("系统审核失败！"+ajaxResult.getMessage());
        }

        //保存car的信息
        car.setCreatetime(new Date());
        car.setState(0L); //0 1
        car.setAuditstate(log.getState()); //0 1 -1
        carMapper.save(car);
        //保存cardetail信息
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        carDetailMapper.save(carDetail);

        //上面没有carId，需要保存后获取再保存日志
        log.setCarId(car.getId());
        logMapper.save(log);
    }

    @Override
    public void update(Car car) {
        super.update(car);
        //也要处理自动审核
    }

    @Transactional
    @Override
    public void autocheck(Car car) {
        //审核
        String text = car.getTitle() +" "+ car.getShopname();
        AjaxResult ajaxResult = baiduAiService.audit(text, car.getCover(), null);
        CarOnlineAuditLog log = new CarOnlineAuditLog();  //审核日志() 上下线日志
        log.setAuditTime(new Date());
        if (ajaxResult.isSuccess()){
            log.setState(1);
            log.setNote("系统审核通过！");
        }else
        {
            log.setState(-1); //
            log.setNote("系统审核失败！"+ajaxResult.getMessage());
        }
        car.setAuditstate(log.getState()); //0 1 -1
        System.out.println("==========");
        System.out.println(car.getId());
        carMapper.update(car);
        System.out.println("==========");
        log.setCarId(car.getId());
        logMapper.save(log);
    }

    @Override
    public void check(Car car) {
        carMapper.checkState(car);
    }
}
